
import dayjs from 'dayjs';
import request from './request';

/* 处理数据html标签显示界面 */
export function removeHTMLTag(htmlstr) {
    let html = htmlstr
        .replace(/<img.*?>/g, "[图片]")
        .replaceAll(/<[^>]+>/g, "")
        .replace(/&nbsp;/gi, "");
    return html;
}

/* 验证是否时间格式：yyyy-MM-dd HH:mm:ss */
export function isValidDateTimeFormat(dateTimeStr) {
    // 使用 Day.js 解析时间字符串，指定格式
    const parsedDate = dayjs(dateTimeStr, 'YYYY-MM-DD HH:mm:ss', true);

    // 检查是否成功解析并且格式正确
    return parsedDate.isValid();
}

/* 压缩图片 */
//压缩图片，返回值是一个包含了file的promise对象
export function compressImage(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
            const img = new Image();
            img.src = event.target.result;
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                const maxSize = 800; // 设置最大宽度和高度
                let width = img.width;
                let height = img.height;

                if (width > height) {
                    if (width > maxSize) {
                        height *= maxSize / width;
                        width = maxSize;
                    }
                } else {
                    if (height > maxSize) {
                        width *= maxSize / height;
                        height = maxSize;
                    }
                }

                canvas.width = width;
                canvas.height = height;

                ctx.drawImage(img, 0, 0, width, height);

                canvas.toBlob((blob) => {
                    const compressedFile = new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() });
                    resolve(compressedFile);
                }, 'image/jpeg', 0.8); // 压缩质量设置为0.8
            };
            img.onerror = error => reject(error);
        };
        reader.onerror = error => reject(error);
    });
}

// 上传图片
export function uploadImage(file) {
    const formData = new FormData();
    formData.append('image', file, file.name);
    return request.post('/upload/image', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

// 图片地址转file对象
//
export function getFileFromUrl(url, fileName) {
    return new Promise((resolve, reject) => {
        var blob = null;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.setRequestHeader('Accept', 'image/png');
        xhr.responseType = "blob";
        // 加载时处理
        xhr.onload = () => {
            // 获取返回结果
            blob = xhr.response;
            let file = new File([blob], fileName, { type: 'image/png' });
            // 返回结果
            resolve(file);
        };
        xhr.onerror = (e) => {
            reject(e)
        };
        // 发送
        xhr.send();
    });
}


